package com.atguigu.guli.service.oss.service.impl;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.atguigu.guli.service.oss.util.OssProperties;
import com.atguigu.guli.service.oss.service.FileService;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.InputStream;
import java.util.UUID;
@Service
public class FileServiceImpl implements FileService {
    @Autowired
    OssProperties ossProperties;

    @Override
    public String upload(InputStream inputStream, String module, String oFilename) {

// 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(ossProperties.getEndpoint(), ossProperties.getKeyId(), ossProperties.getKeySecret());

// 填写本地文件的完整路径。如果未指定本地路径，则默认从示例程序所属项目对应本地路径中上传文件流。

// 依次填写Bucket名称（例如examplebucket）和Object完整路径（例如exampledir/exampleobject.txt）。Object完整路径中不能包含Bucket名称。
        String folder = new DateTime().toString("yyyy/MM/dd");
        //文件扩展名
        String fileName = UUID.randomUUID().toString();
        String fileExtension = oFilename.substring(oFilename.lastIndexOf("."));
        String key = module+"/"+folder+"/"+fileName+fileExtension;
        ossClient.putObject(ossProperties.getBucketName(), key, inputStream);

// 关闭OSSClient。
        ossClient.shutdown();
        return "https://" + ossProperties.getBucketName() + "." + "oss-cn-shanghai.aliyuncs.com" + "/" + key;
    }

    //删除云库中的头像信息
    @Override
    public String deleteFromAliyun(String url) {
        String endpoint = ossProperties.getEndpoint();
        String accessKeyId = ossProperties.getKeyId();
        String accessKeySecret = ossProperties.getKeySecret();

        String bucketName = ossProperties.getBucketName();
        String host = "https://" + ossProperties.getBucketName() + "." + "oss-cn-shanghai.aliyuncs.com"+ "/";
        String objectName = url.substring(host.length());
        System.out.println(objectName);
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        ossClient.deleteObject(bucketName, objectName);
        ossClient.shutdown();
        return url;
    }


}
